package com.easy.project.base.validate.validator;

import com.easy.project.base.validate.DateFormatValidate;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.text.ParseException;
import java.text.SimpleDateFormat;

/**
 * 枚举验证器
 * @author wxz
 */
@Slf4j
public class DateFormatValidator implements ConstraintValidator<DateFormatValidate,Object> {

    private String format;

    @Override
    public boolean isValid(Object val, ConstraintValidatorContext constraintValidatorContext) {
        if (StringUtils.isBlank(format)){
            return true;
        }
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format);
        try {
            // 判断长度是否和格式一样
            String valStr = String.valueOf(val);
            if (valStr.length() != format.length()){
                return false;
            }
            simpleDateFormat.parse(valStr);
        } catch (ParseException e) {
            log.error("日期格式校验失败：",e);
            return false;
        }
        return true;
    }

    @Override
    public void initialize(DateFormatValidate constraintAnnotation) {
        this.format = constraintAnnotation.format();
    }

}
